package com.project.web.admin.controller.common;

import com.project.model.core.Admin;
import com.project.web.admin.service.core.AdminService;
import com.project.web.admin.utils.shiro.Principal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.yun.common.utils.webeditor.DateEditor;

import javax.annotation.Resource;
import java.util.Date;

/**
 * controller父类
 */
public abstract class BaseController extends AbstractController {

    @Resource(name = "adminServiceImpl")
    private AdminService adminService;

    /**
     * 错误视图
     */
    protected static final String ERROR_VIEW = "/intfc/config/error.ftl";

    /**
     * 弹出layer视图并自动关闭弹出层（iframe层）
     */
    protected static final String LAYER_FORWARD_VIEW = "/intfc/config/layerForward.ftl";

    /**
     * 数据绑定
     *
     * @param binder WebDataBinder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Date.class, new DateEditor(true));
    }

    /**
     * 获取当前登录的用户
     *
     * @return
     */
    public Admin getCurrentAdmin() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            Principal principal = (Principal) subject.getPrincipal();
            if (principal != null) {
                return adminService.getById(principal.getId());
            }
        }
        return null;
    }

    /**
     * 获取当前登录的用户ID
     *
     * @return
     */
    public Long getCurrentAdminId() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            Principal principal = (Principal) subject.getPrincipal();
            if (principal != null) {
                return principal.getId();
            }
        }
        return null;
    }

}
